<!--<template>
    <a-upload
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            action="http://127.0.0.1:8888/upload"
            :headers="headers"
            @change="handleChange"
    >
        <a-button>
            <upload-outlined /> Click to Upload </a-button>
    </a-upload>

</template>-->
<template>
    <div class="clearfix">
        <a-upload-dragger
                :fileList="fileList"
                :remove="handleRemove"
                :beforeUpload="beforeUpload"
        >
            <p class="ant-upload-drag-icon">
                <inbox-outlined/>
            </p>
            <p class="ant-upload-text">
                Click or drag file to this area to upload
            </p>
            <p class="ant-upload-hint">
                Support for a single or bulk upload. Strictly prohibit from uploading company data or other
                band files
            </p>
        </a-upload-dragger>
        <a-button
                type="primary"
                :disabled="fileList.length === 0"
                :loading="uploading"
                style="margin-top: 16px"
                @click="handleUpload"
        >
            {{ uploading ? 'Uploading' : 'Start Upload' }}
        </a-button>
    </div>


    
    <uploader
            ref="uploader"
            :options="options"
            :autoStart="false"
            @file-added="onFileAdded"
            fileStatusText="fileStatusText"
            class="uploader-app">
        <uploader-unsupport></uploader-unsupport>
        <uploader-drop>
            <p>拖动文件</p>
            <uploader-btn>选择文件</uploader-btn>
        </uploader-drop>
        <uploader-list></uploader-list>
        <p>文件处理状态：{{status}}</p>
        <p>文件上传进度：{{progress}}%</p>
    </uploader>
</template>





<script>
    import SparkMD5 from 'spark-md5';
    import http from 'axios'
    import uploader from 'vue-simple-uploader'
    const MinIO = require('minio')
    import Fs from 'fs'
    import {message} from 'ant-design-vue';
    import {InboxOutlined} from '@ant-design/icons-vue';
    import {defineComponent, ref, toRefs, reactive, onMounted} from "vue";

    export default defineComponent({
        components: {
            InboxOutlined,
        },
        setup: function () {
            let c = reactive({});
            onMounted(() => {
                c = new MinIO.Client({
                    endPoint: '172.20.3.19',
                    port: 9000,
                    useSSL: false,
                    accessKey: 'test',
                    secretKey: 'test@osskey/pwd'
                });
                /*  c =  new MinIO.Client({
                      endPoint: 'play.min.io',
                      port: 9000,
                      useSSL: true,
                      accessKey: 'Q3AM3UQ867SPQQA43P2F',
                      secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
                  });*/
                c.bucketExists('oss', function (err, exists) {
                    if (err) {
                        return console.log(err)
                    }
                    if (!exists) {
                        c.makeBucket('oss', function (err) {
                            console.log('Bucket created successfully')
                        })
                    }
                })
            })

            //文件初始化 查询所有已经上传得文件列表
            let fileList = ref([]);
            let uploading = ref(false);
            const headers = reactive({
                authorization: 'authorization-text',
            });
            const handleChange = (info) => {
                if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} file upload failed.`);
                }
            }
            const beforeUpload = (file) => {
                console.log('=======3', file)
                fileList.value = [...fileList.value, file];
                //computeMD5(file);

                return false;
            }

            const handleRemove = (file) => {
                const index = fileList.value.indexOf(file);
                const newFileList = fileList.value.slice();
                newFileList.splice(index, 1);
                fileList.value = newFileList;
            }
            const handleUpload = async () => {
                fileList.value.forEach((file) => {
                    let fileReader = new FileReader()
                     fileReader.readAsText(file)
                        fileReader.onload = (e)=>{
                        console.log('========fffff',e)
                        c.putObject("oss", file.name, e.target.result, file.size, (err, etag) => {
                         console.log(err, etag)
                    });
                }
                })

                /*const formData = new FormData();
                fileList.value.forEach(f => {
                    formData.append('files', f);
                });
                uploading.value = true;
                http({
                    url: 'http://127.0.0.1:8888/upload',
                    method: 'post',
                    data: formData,
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }).then(res => {
                    if (res.status === 200){
                        uploading.value = false;
                        message.success('upload successfully.');
                    }else {
                        uploading.value = false;
                        message.error('upload failed.');
                    }
                })*/
            }

            const computeMD5 = (file) => {
                let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                    chunkSize = 1024 * 5 * 10,
                    chunks = Math.ceil(file.size / chunkSize),
                    currentChunk = 0,
                    spark = new SparkMD5.ArrayBuffer(),
                    fileReader = new FileReader();

                let time = new Date().getTime();
                console.log('计算MD5...', chunks)
                file.totalChunkCounts = chunks;
                loadNext();
                fileReader.onload = (e) => {
                    console.log("==========444", e)
                    spark.append(e.target.result);   // Append array buffer
                    currentChunk++;

                    if (currentChunk < chunks) {
                        console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk + 1}/${chunks}分片解析`);
                        loadNext();
                    } else {
                        let md5 = spark.end();
                        console.log(`MD5计算完成：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${(new Date().getTime() - time) / 1000} s`);
                        spark.destroy(); //释放缓存
                        file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
                        file.cmd5 = false; //取消计算md5状态
                        console.log("==========55555", file)

                        computeMD5Success(file);
                    }
                };

                fileReader.onerror = () => {
                    console.warn('oops, something went wrong.');
                    file.cancel();
                };

                function loadNext() {
                    let start = currentChunk * chunkSize;
                    let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                    fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                }
            }
            const computeMD5Success = async (file) => {
                /** 未上传 */
                if (file.uploadID == "" || file.uuid == "") {
                    newMultiUpload(file);
                }

                function addAttachment(file) {
                    return new Promise((resolve, reject) => {
                        axios.post(file.urlPrex + '/add', qs.stringify({
                            uuid: file.uuid,
                            file_name: file.name,
                            size: file.size
                        })).then(function (response) {
                            resolve(response);
                        }).catch(function (error) {
                            console.log(error);
                            reject(error);
                        });
                    })
                }
            }

            const getSuccessChunks = async (file) => {
                return await http.get(`http://127.0.0.1:8888/upload/get_chunks/${file.uniqueIdentifier}`)
                    .then(res => {
                        if (res.status == 200) {
                            file.uploadID = res.data.uploadID;
                            file.uid = res.data.uuid;
                            file.uploaded = res.data.uploaded;
                            file.chunks = res.data.chunks;
                            return file;
                        }
                    })
            }

            const newMultiUpload = (file) => {
                http.post('http://127.0.0.1:8888/upload/new_multipart', {
                    params: {
                        totalChunkCounts: file.totalChunkCounts,
                        md5: file.uniqueIdentifier,
                        size: file.size,
                        fileName: file.name
                    }
                }).then(function (response) {
                    console.log("========>", response)
                    file.uploadID = response.data.uploadID;
                    file.uuid = response.data.uuid;
                })
            }


            const multipartUpload = (file) => {
                let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
                    chunkSize = 1024 * 1024 * 64,
                    chunks = Math.ceil(file.size / chunkSize),
                    currentChunk = 0,
                    fileReader = new FileReader(),
                    time = new Date().getTime();

                function loadNext() {
                    let start = currentChunk * chunkSize;
                    let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

                    fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
                }

                function checkSuccessChunks() {
                    var index = successChunks.indexOf((currentChunk + 1).toString())
                    if (index == -1) {
                        return false;
                    }

                    return true;
                }

                function getUploadChunkUrl(currentChunk, partSize) {
                    http.get(file.urlPrex + '/get_multipart_url', {
                        params: {
                            uuid: file.uuid,
                            uploadID: file.uploadID,
                            size: partSize,
                            chunkNumber: currentChunk + 1
                        }
                    }).then(function (response) {
                        urls[currentChunk] = response.data.url
                        resolve(response);
                    })
                }

                function uploadMinio(url, e) {
                    http.put(url, e.target.result
                    ).then(function (res) {
                        etags[currentChunk] = res.headers.etag;
                        resolve(res);
                    })
                }

                function updateChunk(currentChunk) {
                    http.post(file.urlPrex + '/update_chunk', qs.stringify({
                        uuid: file.uuid,
                        chunkNumber: currentChunk + 1,
                        etag: etags[currentChunk]
                    })).then(function (response) {
                        resolve(response);
                    })
                }

                async function uploadChunk(e) {
                    if (!checkSuccessChunks()) {
                        let start = currentChunk * chunkSize;
                        let partSize = ((start + chunkSize) >= file.size) ? file.size - start : chunkSize;

                        //获取分片上传url
                        await getUploadChunkUrl(currentChunk, partSize);
                        if (urls[currentChunk] != "") {
                            //上传到minio
                            await uploadMinio(urls[currentChunk], e);
                            if (etags[currentChunk] != "") {
                                //更新数据库：分片上传结果
                                //await updateChunk(currentChunk);
                            } else {
                                return;
                            }
                        } else {
                            return;
                        }

                    }

                };
            }
            return {fileList, headers, handleChange, beforeUpload, handleRemove, handleUpload, uploading}
        }
    });
</script>
<!--
<template>
    <a-upload
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            action="http://127.0.0.1:8888/upload"
            :headers="headers"
            @change="handleChange"
    >
        <a-button> <upload-outlined /> Click to Upload </a-button>
    </a-upload>
</template>
<script>
    import { message } from 'ant-design-vue';
    import { UploadOutlined } from '@ant-design/icons-vue';
    export default {
        components: {
            UploadOutlined,
        },
        data() {
            return {
                fileList: [],
                headers: {
                    authorization: 'authorization-text',
                },
            };
        },
        methods: {
            handleChange(info) {
                console.log(info.file.status);

                if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                }
                if (info.file.status === 'done') {
                    message.success(`${info.file.name} file uploaded successfully`);
                } else if (info.file.status === 'error') {
                    message.error(`${info.file.name} file upload failed.`);
                }
            },
        },
    };
</script>-->


